package doan.chuyennganh.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import jxl.write.WriteException;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import doan.chuyennganh.base.DoAnBaseAcitvity;
import doan.chuyennganh.directorychooser.DirectoryChooserFragment;
import doan.chuyennganh.model.AttendanceList;
import doan.chuyennganh.model.ListStudent;
import doan.chuyennganh.util.WriteExcel;
import doan.chuyennganh.util.WriteExcel.OnFinishedWrittingListener;

public class ExportActivity extends DoAnBaseAcitvity implements
		OnClickListener, DirectoryChooserFragment.OnFragmentInteractionListener {
	private RadioGroup rgExportOption;
	private Button btnExport;
	private Button btnChangePath;
	private TextView mDirectoryTextView;
	private EditText mFileNameEditText;
	private DirectoryChooserFragment mDialog;
	private String path = "";
	private String fileName = "file_name";

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.export_activity);
		path = Environment.getExternalStorageDirectory().getAbsolutePath();
		btnExport = (Button) findViewById(R.id.btn_export);
		btnChangePath = (Button) findViewById(R.id.btn_change_path);
		rgExportOption = (RadioGroup) findViewById(R.id.rg_export_file_option);
		btnExport.setOnClickListener(this);
		btnChangePath.setOnClickListener(this);
		mDirectoryTextView = (TextView) findViewById(R.id.tv_save_path);
		mFileNameEditText = (EditText) findViewById(R.id.edt_filename);
		mDialog = DirectoryChooserFragment.newInstance(
				getString(R.string.txt_dirchooser_title), null);
		init();
	}

	public void init() {
		if (ListStudent.getInstance() != null) {
			fileName = "class_" + ListStudent.getInstance().getClassID();
		}
		// ((RadioButton)rgExportOption.findViewById(R.id.rd_excel_xls)).setChecked(true);
		mFileNameEditText.setText(fileName);
		mDirectoryTextView.setText(path);
	}

	private void WriteFile(final String fileName,
			final ArrayList<? extends Object> students,
			final AttendanceList attendances) {
		if (students == null || fileName == "" || fileName == null) {
			return;
		}
		final File file = new File(fileName);
		File files = new File(path);
		File listFileName[] = files.listFiles();
		int i = 0;
		for (; i < listFileName.length; i++) {
			if (listFileName[i].getName().equalsIgnoreCase(file.getName())) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(getString(R.string.txt_warning_dialog_title));
				builder.setMessage(getString(R.string.txt_same_file_name));
				builder.setCancelable(false);
				builder.setPositiveButton(getString(R.string.txt_I_know),
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								WriteExcel writeListStudent = new WriteExcel(
										fileName);
								try {
									writeListStudent.write(students,
											attendances,
											new OnFinishedWrittingListener() {

												@Override
												public void OnFinished() {
													Intent intent = new Intent(
															Intent.ACTION_VIEW);
													intent.setDataAndType(
															Uri.fromFile(file),
															"application/vnd.ms-excel");

													Intent chooserIntent = Intent
															.createChooser(
																	intent,
																	getString(R.string.txt_app_chooser_title));
													startActivity(chooserIntent);
												}
											});
								} catch (WriteException | IOException e) {
									e.printStackTrace();
								}

							}

						});
				builder.setNegativeButton(getString(R.string.txt_cancel),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				AlertDialog dialog = builder.create();
				dialog.show();

				break;
			}
		}
		if (i == listFileName.length) {
			WriteExcel writeListStudent = new WriteExcel(fileName);
			try {
				writeListStudent.write(students, attendances,
						new OnFinishedWrittingListener() {

							@Override
							public void OnFinished() {
								Intent intent = new Intent(Intent.ACTION_VIEW);
								intent.setDataAndType(Uri.fromFile(file),
										"application/vnd.ms-excel");

								Intent chooserIntent = Intent
										.createChooser(
												intent,
												getString(R.string.txt_app_chooser_title));
								startActivity(chooserIntent);
							}
						});
			} catch (WriteException | IOException e) {
				e.printStackTrace();
			}

		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_export: {
			switch (rgExportOption.getCheckedRadioButtonId()) {
			case R.id.rd_excel_xls:
				String fullFileName = mDirectoryTextView.getText().toString()
						+ "/" + mFileNameEditText.getText().toString() + ".xls";
				WriteFile(fullFileName, ListStudent.getInstance()
						.getAllStudents(), ListStudent.getInstance()
						.getAttendanceList());
				break;
			case R.id.rd_excel_xlsx:
				fullFileName = mDirectoryTextView.getText().toString() + "/"
						+ mFileNameEditText.getText().toString() + ".xlsx";
				WriteFile(fullFileName, ListStudent.getInstance()
						.getAllStudents(), ListStudent.getInstance()
						.getAttendanceList());
				break;
			default:
				break;
			}
			break;
		}
		case R.id.btn_change_path:
			mDialog.show(getFragmentManager(), null);
			break;

		default:
			break;
		}
	}

	@Override
	public void onSelectDirectory(String path) {
		this.path = path;
		mDirectoryTextView.setText(path);
		mDialog.dismiss();
	}

	@Override
	public void onCancelChooser() {
		mDialog.dismiss();
	}
}
